<?php
/**
* @author		Arunoda Susiripala
* @package		jconnect
* @copyright	Arunoda Susiripala
* @license 		http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
*/

class User{
	private $usersave;
	public $username;
	public $email;
	public $password;

	private $dbConn;

	function __construct($username=null){
		global $db_user,$db_host,$db_name,$db_password;
		$dbConn = mysql_connect($db_host, $db_user, $db_password)
		or die('Could not connect: ' . mysql_error());
		mysql_select_db($db_name) or die('Could not select database');
		if($username){
			$sql="select * from users where username='" . $username ."'";
			$result = mysql_query($sql);
			if(mysql_num_rows($result)==1){
				$row=mysql_fetch_row($result);
				$this->username=$row[1];
				$this->email=$row[2];
				$this->password=$row[3];
				$this->usersave=$row[1];
			}
			else{
				throw new Exception('No User Found');
			}
		}
	}

	function save(){
		$sql="select * from users where username='" . $this->usersave ."'";
		$result = mysql_query($sql);
		$num_rows=mysql_num_rows($result);
		
		if($num_rows==1){ //to Update
			$sql="UPDATE users SET " .
				"email='$this->email',password='$this->password' WHERE username='$this->username'";
			if(!mysql_query($sql)){
				throw new Exception("<".mysql_errno().">".mysql_error());
			}
		}
		else if($num_rows==0){ // to Insert
			$sql="INSERT INTO users(username,email,password) VALUES(".
				"'$this->username','$this->email','$this->password'".
				")";
			if(!mysql_query($sql)){
				throw new Exception("<".mysql_errno().">".mysql_error());
			}
		}
		else{
			throw new Exception('Multiple User Found');
		}
		
		$this->usersave=$this->username;
	}
	
	function delete(){
		$sql="DELETE from users WHERE username='$this->username'";
		if(!mysql_query($sql)){
			throw new Exception(mysql_error());
		}
	}
	
	static function getUsernames(){
		// to load the mysql...
		$user=new User();
		
		$sql="select username from users";
		$result = mysql_query($sql);
		if(!mysql_query($sql)){
			throw new Exception(mysql_error());
		}
		$usrNames=array();
		$lc=0;
		while(($row=mysql_fetch_row($result))){
			$usrNames[$lc++]=$row[0];
		}
		
		return $usrNames;
	}

}

?>
